{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "#数据集的准备\n",
    "import torch.utils.data as Data  \n",
    "from _01XlsReader import XlsReader as reader\n",
    "\n",
    "database=reader(8,2,normalmode=\"m-scaler\") #读取数据,同时进行归一化\n",
    "train_num=int(1*database.groupnum)\n",
    "test_num=database.groupnum-train_num\n",
    "\n",
    "batchsize=10\n",
    "#生成训练集\n",
    "train_features=database.features[0:train_num]\n",
    "train_labels=database.labels[0:train_num]\n",
    "dataset=Data.TensorDataset(train_features,train_labels)\n",
    "train_iter=Data.DataLoader(dataset,batchsize,shuffle=True,num_workers=0)\n",
    "\n",
    "#生成验证集\n",
    "test_features=database.features[0:train_num]#[train_num:train_num+test_num]\n",
    "test_labels=database.labels[0:train_num]#[train_num:train_num+test_num]\n",
    "dataset=Data.TensorDataset(test_features,test_labels)\n",
    "test_iter=Data.DataLoader(dataset,batchsize,shuffle=True,num_workers=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "#填入网络具体参数\n",
    "from _02Netbase import BP,ResNet\n",
    "from torch import nn\n",
    "\n",
    "\n",
    "\n",
    "node=[8,50,50,20,2]\n",
    "act=[nn.ReLU6(),nn.ReLU(),nn.ReLU()]\n",
    "\n",
    "bp=BP(node,act)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "#设置训练参数\n",
    "import torch\n",
    "epcho=400\n",
    "lr=1e-4\n",
    "#选择优化器\n",
    "optimizer=torch.optim.Adam(params=bp.parameters(),lr=lr)\n",
    "Loss=nn.MSELoss() #选择损失函数\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "device=torch.device(\"cpu\")\n",
    "bp=bp.to(device)\n",
    "Loss=Loss.to(device)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "#开始训练\n",
    "import time\n",
    "\n",
    "total_train_step=0\n",
    "total_test_step=0\n",
    "bp.eval()\n",
    "start_time=time.time()\n",
    "\n",
    "logpath=\"log\\\\{}.txt\".format(start_time)\n",
    "file=open(logpath,'w')\n",
    "logcontent=\"\"\n",
    "\n",
    "for i in range(epcho):\n",
    "    for data in train_iter:\n",
    "        features,targets=data\n",
    "        features=features.to(device)\n",
    "        targets=targets.to(device)\n",
    "        outputs=bp(features)\n",
    "        loss=Loss(outputs,targets)\n",
    "        optimizer.zero_grad()\n",
    "        loss.backward()\n",
    "        optimizer.step()        \n",
    "        total_train_step+=1\n",
    "    total_test_loss=0\n",
    "    with torch.no_grad():\n",
    "        for data in test_iter:\n",
    "            features,targets=data\n",
    "            features=features.to(device)\n",
    "            targets=targets.to(device)\n",
    "            outputs=bp(features)\n",
    "            loss=Loss(outputs,targets)\n",
    "            total_test_loss+=loss.item()\n",
    "    src_head=\"第{}轮：\".format(i+1)\n",
    "    src=\"在测试集上的总误差:{}\".format(total_test_loss)\n",
    "    logcontent+=(src_head+src+\"\\n\")\n",
    "\n",
    "end_time=time.time() \n",
    "totaltime=\"{:.3f}\".format(end_time-start_time)\n",
    "log=\"batchsize: {}\\nepcho: {}\\nlr: {}\\ntotal_time: {}s\\n\".format(batchsize,epcho,lr,totaltime)\n",
    "file.write(log+logcontent)\n",
    "file.close() "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "modelpath=\"model\\\\model_01.pth\"\n",
    "torch.save(bp,modelpath)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[5.0653043 4.6147976]]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "a=torch.tensor([[1358,2080.0,1310,1559,2866.0,3121,1300,1475]])\n",
    "database.normalFeature(a)\n",
    "a=a.to(device)\n",
    "b=bp(a)\n",
    "b=b.to(torch.device('cpu'))\n",
    "b=b.detach().numpy()\n",
    "#database.denormalTarget(b)\n",
    "\n",
    "print(b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2.0\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "lis=[[int(2),int(3)]]\n",
    "k=torch.tensor(lis)\n",
    "print(float(k[0,0]))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "space_1",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.15"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "28a6b64d7a9bb6f666d78475bbc3e5dc595befbf0f64535b24791084d45e1764"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
